package org.client.iot.ui.device.network;

import android.annotation.SuppressLint;
import android.widget.RadioGroup;

import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;

import org.client.iot.R;
import org.client.iot.databinding.ActivityManualNetworkBinding;
import org.client.iot.domain.DeviceInfoDto;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseDevReq;
import org.tzw.template.base.BaseActivity;

import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @Date 2025/8/19 17:21
 * @Description 手动入网
 */

public class ManualNetworkActivity extends BaseActivity<ActivityManualNetworkBinding> {
    private MiniLoadingDialog mMiniLoadingDialog;
    private String cloudStatus = "启用";
    private DeviceInfoDto deviceInfoDto;

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarManualNetwork.toolbarPageHead);
        mRoot.toolbarManualNetwork.textViewTitle.setText("手动入网");
//        mRoot.txtNetworkAccessStatus.setText("获取中...");
        showLoading("获取设备信息中..");
        getDevInfo();
    }

    @Override
    protected void initListener() {
        mRoot.toolbarManualNetwork.imgBack.setOnClickListener(v -> finish());
        mRoot.rgCloudStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_cloud_status_enable) {
                    cloudStatus = "启用";
                } else {
                    cloudStatus = "未启用";
                }
                LogUtils.i("云端状态选择: ", cloudStatus);
            }
        });
        mRoot.btnManualNetwork.setOnClickListener(v -> {
            if (cloudStatus == null || cloudStatus.isEmpty()) {
                showToastShort("请选择云端状态");
                return;
            }
            showLoading("手动入网中..");
            manualNetworkAccess(cloudStatus);
        });
    }

    // 手动入网
    private void manualNetworkAccess(String networkAccess) {
        String params = FastjsonUtils.toJsonString(manualNetworkAccessParams(networkAccess));
        Observable<BaseDevReq<Object>> compose =
                NetworkApi.createService(ApiService.class, "dev").manualNetworkAccess
                                (RequestBody.create(MediaType.parse("application/json"), params))
                        .compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
                            @SuppressLint("CheckResult")
                            @Override
                            public void onSuccess(BaseDevReq<Object> req) {
                                if (req == null) {
                                    return;
                                }
                                runOnUiThread(() -> {
                                    disLoading();
                                    LogUtils.i("手动入网接口req==", req.toString());
                                    showToastLong(req.getMessage());
                                });

                            }

                            @SuppressLint("CheckResult")
                            @Override
                            public void onFailure(Throwable e) {
                                runOnUiThread(() -> {
                                            disLoading();
                                            showToastLong(e.getMessage());
                                        }
                                );

                            }
                        }));
    }

    // 获取设备信息
    private void getDevInfo() {
        Observable<BaseDevReq<DeviceInfoDto>> compose = NetworkApi.createService(ApiService.class, "dev")
                .getDevInfo().compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<DeviceInfoDto>>() {
                    @SuppressLint({"CheckResult", "SetTextI18n"})
                    @Override
                    public void onSuccess(BaseDevReq<DeviceInfoDto> req) {
                        if (req == null) {
                            return;
                        }
                        runOnUiThread(() -> {
                            disLoading();
                            LogUtils.i("获取设备信息req==", FastjsonUtils.toJsonString(req.getData()));
                            if (req.getData() == null) {
                                showToastLong("获取设备信息失败");
                                return;
                            }
                            deviceInfoDto = req.getData();
                            mRoot.txtNetworkAccessStatus.setText(req.getData().getNetworkAccessStatus() == null ? "" : req.getData().getNetworkAccessStatus());
                        });
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        runOnUiThread(() -> {
                                    disLoading();
                                    showToastLong(e.getMessage());
                                }
                        );
                    }

                }));
    }

    private Map<String, Object> manualNetworkAccessParams(String networkAccess) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("networkAccess", networkAccess);
        return params;
    }


    private void showLoading(String msg) {
        runOnUiThread(() -> {
            mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, msg);
            mMiniLoadingDialog.show();
        });
    }

    private void disLoading() {
        runOnUiThread(() -> {
            if (mMiniLoadingDialog != null) {
                mMiniLoadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disLoading();
    }
}
